import React, {useCallback, useEffect, useState} from "react";
import styled from "@emotion/styled";
import {Button, Input, message, Popconfirm, Space, Spin, Table, Tooltip} from "antd";
import {PlusOutlined, ReloadOutlined, LeftOutlined, CaretRightOutlined, DeleteOutlined, StopOutlined, EditOutlined, PoweroffOutlined, EyeOutlined } from "@ant-design/icons";
import {ColumnsType} from "antd/es/table";
import {httpGet, httpPost, ResponseData, ResponsePage} from "../../../utils/https";
import {CustomizeCreate} from "./create";
import {useHistory} from "react-router-dom";
import {useSelector} from "../../../hooks/useRedux";
import { ExecLogger } from "../logger";


export interface CustomizeFields {
    id: number;
    group_id: number;
    title: string;
    status: "running" | "ending" | "waiting"
    script: string;
    desc: string;
    run_time: string;
    run_len: number;
    base_path: string;
    linking: string;
    log_path: string;
    exec_way: string;
    log_type: 'static' | 'real_time';
    log_read_line: number;
}

interface ParamData {
    page: number;
    size: number;
    total: number;
    title: string;
    data: CustomizeFields[]
}


export const CustomizeService:React.FC = () => {

    let history = useHistory();

    let group = useSelector((state) => state.customize.group);

    const columns: ColumnsType<CustomizeFields> = [
        {
            key: 'title',
            title: '服务名称',
            dataIndex: 'title',
            align: 'center'
        },
        {
            key: 'desc',
            title: '描述',
            align: 'center',
            dataIndex: 'desc',
        },
        {
            key: 'status',
            title: '状态',
            dataIndex: 'status',
            align: 'center'
        },
        {
            key: 'run_len',
            title: '运行时长',
            dataIndex: 'run_len',
            align: 'center'
        },
        {
            key: 'run_time',
            title: '运行时间',
            dataIndex: 'up_time',
            align: 'center',
            width: 200
        },
        {
            key: 'action',
            title: '操作',
            align: 'center',
            width: 200,
            render: (recode:CustomizeFields) => (
                <Space>
                    <Tooltip title="执行" color='#595959' key='#595959'>
                        <Button size="middle" type="primary" onClick={() => execScript(recode.id)} icon={<CaretRightOutlined />} />
                    </Tooltip>
                    <Tooltip title="终止" color='#595959' key='#595959'>
                        <Button size="middle" type="primary" className="button-color-gray" icon={<PoweroffOutlined />} />
                    </Tooltip>
                    <Tooltip title="日志" color='#595959' key='#595959'>
                        <Button size="middle" type="primary" icon={<EyeOutlined />} onClick={() => openLogger(recode)}/>
                    </Tooltip>
                    <Tooltip title="编辑" color='#595959' key='#595959'>
                        <Button size="middle" type="primary" className="button-color-green" onClick={() => openUpdate(recode)} icon={<EditOutlined />} />
                    </Tooltip>
                    <Tooltip title="删除" color='#595959' key='#595959'>
                        <Popconfirm placement="top" title="是否删除当前服务？" okText="删除" cancelText="取消" onConfirm={() => deleteServer(recode.id)}>
                            <Button size="middle" type="primary" danger icon={<DeleteOutlined />} />
                        </Popconfirm>
                    </Tooltip>
                </Space>
            )
        }
    ]

    const [visible, setVisible] = useState<boolean>(false)
    const [logVisible, setLogVisible] = useState<boolean>(false)
    const [currId, setCurrId] = useState<number>(0)

    const [spinning, setSpinning] = useState<boolean>(false)

    const [currData, setCurrData] = useState<CustomizeFields>({
        id: 0,
        group_id: 0,
        title: '',
        status: 'waiting',
        script: '',
        desc: '',
        run_time: '',
        run_len: 0,
        base_path: '',
        linking: '',
        log_path: '',
        exec_way: '',
        log_type: 'static',
        log_read_line: 1000
    })

    const [params, setParam] = useState<ParamData>({
        page: 1,
        size: 10,
        total: 0,
        title: '',
        data: []
    })

    const loadData = (page: number, size: number, title?: string) => {
        setSpinning(true)
        httpPost<ResponseData<ResponsePage<CustomizeFields[]>>, any>('/customize/list', {
            group_id: group.id,
            page: page,
            size: size,
            title: title
        }).then(res => {
            setSpinning(false)
            setParam({...params, data: res.data.content, total: res.data.total})
        })
    }

    const refresh = () => {
        const {page, size, title} = params
        loadData(page, size, title)
    }

    const execScript = (id: number) => {
        httpGet<ResponseData<string>, any>('/customize/running', {id: id}).then(res => {
            message.success(res.data)
        })
    }

    const deleteServer = (id: number) => {
        httpGet<ResponseData<string>, any>('/customize/delete', {id: id}).then(res => {
            if (res.code === '001001200') {
                message.success(res.msg)
                refresh()
            } else {
                message.error(res.msg)
            }
        })
    }

    const openUpdate = (data: CustomizeFields) => {
        setVisible(true)
        setCurrData(data)
    }


    const openLogger = (data: CustomizeFields) => {
        setCurrId(data.id)
        setLogVisible(true)
    }

    const closeModel = () => {
        setVisible(false)
        refresh()
    }

    useEffect(() => {
        loadData(1, 10)
    }, [])

    return <Container>
        <Space style={{marginBottom: 1 + 'rem'}}>
            <Button size="middle" type="primary" icon={<LeftOutlined />} onClick={() => history.push('/customize/group')} />
            <Button size="middle" type="primary" icon={<PlusOutlined />} onClick={() => setVisible(true)}>增加</Button>
            <Button size="middle" type="primary" className="button-color-green" icon={<ReloadOutlined />} onClick={refresh}>刷新</Button>
            <Input.Search placeholder="请输入搜索的服务名称" size="middle" enterButton />
        </Space>
        <Spin tip="正在加载数据......" spinning={spinning}>
            <Table columns={columns} bordered dataSource={params.data} />
        </Spin>

        <CustomizeCreate data={currData} visible={visible} onCancel={closeModel} />
        <ExecLogger visible={logVisible} data={currId} onCancel={() => setLogVisible(false)} />
    </Container>

}

const Container = styled.div`
  margin: 24px;
`